//
//  AlbumController.swift
//  hello
//
//  Created by 赵康 on 2024/11/11.
//
import Vapor
import Fluent
import Redis

extension AlbumController {
	struct SearchQuery: Content {
		let search: String
		var page: Int = 1
		var per: Int = 20
		var category: Album.Category?
		var tagName: String?
		var sortBy: SortField = .updatedAt
		var order: SortOrder = .descending
		var searchScope: SearchScope = .all
		var searchField: SearchField?
		var effectiveSearchScope: SearchScope {
			if searchField == .author {
				return .audios
			} else {
				return searchScope
			}
		}
	}
	enum SearchField: String, Content {
		case title
		case description
		case author
		case all
	}
	enum SortField: String, Content {
		case updatedAt
		case playCount
		case favoriteCount
		case title
		case duration
	}
	enum SortOrder: String, Content {
		case ascending
		case descending
	}
	enum SearchScope: String, Content {
		case all
		case albums
		case audios
	}
	struct TagQuery: Content {
		var page: Int?
		var per: Int?
	}
	struct FetchQuery: Content {
		var page: Int = 1
		var per: Int = 20
	}
		// 修改包含最近音频的响应结构
	struct AlbumWithRecentAudioResponse: Content {
		var albums: Page<AlbumResponse>
		let recentAudios: [Audio]
	}
	struct SearchResponse: Content {
		var albums: Page<AlbumResponse>
		var audios: Page<AudioSearchResponse>
	}
		// 转换函数
		// 修改 convertToResponse 方法中的收藏状态获取部分
	func convertToResponse(albums: [Album], userID: UUID?, req: Request) async throws -> [AlbumResponse] {
		var favoriteStatus: [UUID: Bool] = [:]
		
			// 获取收藏状态
		if let userID = userID {
			let validAlbumIds = albums.compactMap { $0.id }
			
			if !validAlbumIds.isEmpty {
				let favorites = try await Favorite.query(on: req.db)
					.filter(\.$user.$id == userID)
					.filter(\.$album.$id ~~ validAlbumIds)
					.all()
				
				for favorite in favorites {
					favoriteStatus[favorite.$album.id] = true
				}
			}
		}
		
			// 转换为响应模型
		return albums.map { album in
			AlbumResponse(
				id: album.id,
				title: album.title,
				description: album.description,
				cover: album.cover,
				audioCount: album.audioCount,
				playCount: album.playCount,
				favoriteCount: album.favoriteCount,
        wordCount: album.wordCount,
				category: album.category,
				isFavorite: album.id.flatMap { favoriteStatus[$0] } ?? false,
				tags: album.tags.map { TagResponse(id: $0.id, name: $0.name) },
				createdAt: album.createdAt,
				updatedAt: album.updatedAt
			)
		}
	}

	
		// 分页转换函数
	func convertToResponsePage(pageResponse: Page<Album>, userID: UUID?, req: Request) async throws -> Page<AlbumResponse> {
		let convertedItems = try await convertToResponse(albums: pageResponse.items, userID: userID, req: req)
		return Page(
			items: convertedItems,
			metadata: pageResponse.metadata
		)
	}
	
	func escapeSQLString(_ string: String) -> String {
		return string.replacingOccurrences(of: "'", with: "''")
			.replacingOccurrences(of: "\\", with: "\\\\")
	}
}
